<template>
  <div v-if="hasData" id="viewer-container">
    <div v-if="!isLoading" id="images-container">
      <ImageUnit
        v-for="image in imagesData"
        :key="image.id"
        :imageData="image"
        @delete-image="refresh"
      ></ImageUnit>
    </div>
    <el-skeleton v-else :rows="15" :throttle="500" animated style="margin-top: 30px; width: 1800px" />
  </div>
  <div v-else style="height: 600px">
    <el-empty style="height: 100%; width: 100%" description="没有数据" />
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from "vue"
import emitter from "@/utils/mitt"
import ImageUnit from "./ImageUnit.vue"
import { filterImagesApi, getImagesApi, searchImagesApi } from "@/api/data-manager/imageApi"
import { ElMessage } from "element-plus"

const imagesData = ref<any>()

const hasData = ref<boolean>(true)
const isLoading = ref<boolean>(true)

type modeType = "search" | "filter" | "browse"

let currentData: any
let currentPage: number
let currentPageSize: number
let currentMode: modeType

onMounted(() => {
  emitter.on("DM:page-change", (data: any) => {
    const info = data.data
    if (info) {
      currentMode = data.type
      currentPage = data.page
      currentPageSize = data.size
      setTimeout(async () => {
        switch (data.type as modeType) {
          case "browse": {
            currentData = info.id
            break
          }
          case "search": {
            currentData = info.data
            break
          }
          case "filter": {
            currentData = info
            break
          }
        }
        refresh()
      })
    } else {
      hasData.value = false
      isLoading.value = false
    }
  })
})

function refresh() {
  setTimeout(async () => {
    isLoading.value = true
    let res
    try {
      switch (currentMode as modeType) {
        case "browse": {
          res = await getImagesApi(currentData, currentPage, currentPageSize)
          break
        }
        case "search": {
          res = await searchImagesApi(currentData, currentPage, currentPageSize)
          emitter.emit("DM:image-amount", res.data.imageAmount)
          break
        }
        case "filter": {
          res = await filterImagesApi(currentData, currentPage, currentPageSize)
          emitter.emit("DM:image-amount", res.data.imageAmount)
          break
        }
      }
    } catch (error) {
      hasData.value = false
      isLoading.value = false
      ElMessage.error("获取图片列表失败，请稍后再试")
      return
    }
    imagesData.value = res.data.imagesInfo
    hasData.value = imagesData.value && imagesData.value.length > 0
    isLoading.value = false
  })
}
</script>

<style lang="scss" scoped>
#images-container {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(4, 1fr);
  justify-content: space-between;
}
</style>
